package xu.ye.view;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.message.BasicNameValuePair;

import xu.ye.R;
import xu.ye.application.MyApplication;
import xu.ye.bean.ContactBean;
import xu.ye.uitl.SDCardUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class HomeSettintActivity extends Activity {

	
	private EditText et_phoneNum;
	private Button btn1_regist;
	private Button btn2_daochu;
	private Button btn3_daoru;
	private Button btn4_backup2net;
	private Button btn5_download2phone;
	
	private MyHandler handler;
	private SDCardUtil sdOp = null;
	private MyApplication application;
	private ProgressDialog pd;
	private AlertDialog.Builder adb;
	private ContentResolver contentR;
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_setting_page);
		application = (MyApplication)getApplication();
		handler = new MyHandler();
		contentR = getContentResolver();
		pd = new ProgressDialog(this);
		adb = new AlertDialog.Builder(this);
		adb.setPositiveButton("确定", null);
		try {
			sdOp = new SDCardUtil();
		} catch (Exception e) {
			e.printStackTrace();
		}
		initView();
		setlistener();
	}

	private void initView() {
		et_phoneNum = (EditText) findViewById(R.id.editText1_phoneNum);
		btn1_regist = (Button) findViewById(R.id.button1_regist);
		btn2_daochu = (Button) findViewById(R.id.button2_daochu);
		btn3_daoru = (Button) findViewById(R.id.button3_daoru);
		btn4_backup2net = (Button) findViewById(R.id.button4_backup2net);
		btn5_download2phone = (Button) findViewById(R.id.button5_download2phone);
	}

	private void setlistener() {
		btn1_regist.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(et_phoneNum.getText().toString().trim().equals("")){
					adb.setMessage("请输入手机号码");
					adb.show();
					return ;
				}
				if(netWorkOK()){
					new SettingsOpRegist().execute("");
				}
				//handler.sendEmptyMessage(MyHandler.WHAT_REGIST);
			}
		});
		btn2_daochu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//handler.sendEmptyMessage(MyHandler.WHAT_CONTACT_EXPORT);
				
				new SettingsOpExport2SDCard().execute("");
			}
		});
		btn3_daoru.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				//handler.sendEmptyMessage(MyHandler.WHAT_CONTACT_IMPORT);
				
				new SettingsOpImport2Phone().execute("");
			}
		});
		btn4_backup2net.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(netWorkOK()){
					new SettingsOpBackup2net().execute("");
				}
				//handler.sendEmptyMessage(MyHandler.WHAT_BACKUP2NET);
			}
		});
		btn5_download2phone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(netWorkOK()){
					new SettingsOpDownload2phone().execute("");
				}
				//handler.sendEmptyMessage(MyHandler.WHAT_DOWNLOAD2PHONE);
			}
		});
	}
	
	private boolean netWorkOK(){
		ConnectivityManager netManager= (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = netManager.getActiveNetworkInfo();
		if(netInfo == null){
			AlertDialog.Builder net = new AlertDialog.Builder(HomeSettintActivity.this);
			
			net.setMessage("请打开网络，才能继续");
			net.setPositiveButton("确定", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					//当网络不可用时，跳转到网络设置页面
		            startActivityForResult(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS), 1);
				}});
			net.setNegativeButton("取消", null);
			net.show();
			
            return false;
		}
		
		return netInfo.isAvailable();
	}

	class SettingsOpRegist extends AsyncTask<Object, Integer, Object>{

		private final int RESPONSECODE_SUC = 0;//注册成功
		private final int RESPONSECODE_REGISTED = 1;//该号码已经注册过
		private final int RESPONSECODE_ERROE = -1;//注册失败
		private final int RESPONSECODE_UNKNOW = 99;//未知错误
		
		@Override
		protected Object doInBackground(Object... objs) {

			AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("phoneNum", et_phoneNum.getText().toString().trim()));
			try {
				HttpEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
				httpPost.setEntity(entity);
				
				HttpResponse response = client.execute(httpPost);
				if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				//正常响应
					int respCode = 0;//解释返回码
					return respCode;
				}else{
					
				}
				
				return Integer.valueOf(RESPONSECODE_UNKNOW);
			} catch (IOException e) {
				e.printStackTrace();
				return e;
			}finally{
				client.close();
			}
		}
		
		@Override
		protected void onPreExecute() {
			pd.setMessage("正在注册中...");
			pd.show();
			super.onPreExecute();
		}
		
		@Override
		protected void onPostExecute(Object result) {
			
			if(result instanceof Exception){
				pd.dismiss();
				adb.setMessage("注册出错，请重新操作！");
				adb.show();
			}else{
				int resp = (Integer)result;
				if(resp == RESPONSECODE_SUC){
					pd.dismiss();
					adb.setMessage("注册成功，直接登录！");
					adb.show();
				}else if(resp == RESPONSECODE_REGISTED){
					pd.dismiss();
					adb.setMessage("该号码已经注册过，直接登录！");
					adb.show();
				}else{
					pd.dismiss();
					adb.setMessage("注册出错，请重新操作！");
					adb.show();
				}
			}
			
		}
	}
	
	class SettingsOpExport2SDCard extends AsyncTask<Object, Integer, Boolean>{

		@Override
		protected Boolean doInBackground(Object... params) {
			
			List<ContactBean>  list= application.getContactBeanList();
			ArrayList<ContactBean> alist = new ArrayList<ContactBean>(list);
			try {
				if(sdOp.write(alist)){
					return true;
				}else{
					return false;
				}
			} catch (IOException e1) {
				e1.printStackTrace();
				return false;
			}
		}
		
		@Override
		protected void onPreExecute() {
			pd.setMessage("正在将联系人导出到SD卡...");
			pd.show();
		}
		@Override
		protected void onPostExecute(Boolean result) {
			
			if(result){
				pd.dismiss();
				adb.setMessage("联系人导出成功！");
				adb.show();
			}else{
				pd.dismiss();
				adb.setMessage("导出失败，请重新操作！");
				adb.show();
			}
			
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}
		
	}
	
	class SettingsOpImport2Phone extends AsyncTask<Object, Integer, Exception>{

		int size = 0;
		@Override
		protected Exception doInBackground(Object... params) {
			
			ArrayList<ContactBean> alistR = null;
			try {
				alistR = sdOp.read();
				size = alistR.size();
				int progress = 0;
				for(ContactBean bean: alistR){
					publishProgress(progress++);
					ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); 
					int rawContactInsertIndex = ops.size(); 
					ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
							.withValue(RawContacts.ACCOUNT_TYPE, null)
							.withValue(RawContacts.ACCOUNT_NAME, null)
							.build()); 
					 ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)   
				                .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)   
				                .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)   
				                .withValue(StructuredName.GIVEN_NAME, bean.getDisplayName())   
				                .build());   
				        ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)   
				                 .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)   
				                 .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)   
				                 .withValue(Phone.NUMBER, bean.getPhoneNum())   
				                 .withValue(Phone.TYPE, Phone.TYPE_MOBILE)   
				                 .build());
				        /*ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)   
				                 .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)   
				                 .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)   
				                 .withValue(Phone.PHOTO_ID, bean.getPhotoId()== null?0:bean.getPhotoId())   
				                 .withValue(Phone.TYPE, Phone.TYPE_MOBILE)   
				                 .build());   */
				        
				        
						try {
							contentR.applyBatch(ContactsContract.AUTHORITY, ops);
						} catch (RemoteException e) {
							e.printStackTrace();
						} catch (OperationApplicationException e) {
							e.printStackTrace();
						}   
				}
				//application.setContactBeanList(alistR);
				
				Intent it1 = new Intent();
				it1.setAction("UPDATE_CONTACT");
				sendBroadcast(it1); 
				return null;
			} catch (Exception e) {
				return e;
			} 
					
		}
		@Override
		protected void onPreExecute() {
			pd.setMessage("正在将联系人导入手机...");
			pd.setCancelable(false);
			pd.setCanceledOnTouchOutside(false);
			pd.show();
		}
		@Override
		protected void onPostExecute(Exception result) {
			pd.dismiss();
			if(result == null){
				adb.setMessage("导入联系人成功！");
			}else 
			if(result instanceof FileNotFoundException){
				adb.setMessage("没有找到备份的文件，导入联系人失败！");
			}else {
				adb.setMessage("文件错误，不能正常导入联系人！");
			}
			adb.show();
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			pd.setProgress(values[0]);
			pd.setMessage("正在将联系人导入手机...\n"+values[0]+"/"+size);
			super.onProgressUpdate(values);
		}
	}
	
	class SettingsOpBackup2net extends AsyncTask<Object, Integer, Exception>{

		@Override
		protected Exception doInBackground(Object... objs) {

			AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("phoneNum", objs[0].toString()));
			
			try {
				HttpEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
				httpPost.setEntity(entity);
				
				HttpResponse response = client.execute(httpPost);
				if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				//正常响应	
					byte[]data = null;//读取文件数据
					AbstractHttpEntity eData = AndroidHttpClient.getCompressedEntity(data, contentR);
					httpPost.setEntity(eData);
					HttpResponse sendData = client.execute(httpPost);//
					
				}else{
					
				}
			} catch (IOException e) {
				e.printStackTrace();
				return e;
			}finally{
				client.close();
			}
		
			
			return null;
		}
		
		@Override
		protected void onPreExecute() {
			pd.setMessage("正在将联系人上传到云端...");
			pd.show();
		}
		
		@Override
		protected void onPostExecute(Exception result) {
			if(result == null){
				pd.dismiss();
				adb.setMessage("成功备份到云端！");
				adb.show();
			}else{
				pd.dismiss();
				adb.setMessage("备份失败，请重新操作！");
				adb.show();
			}
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
	}
	
	class SettingsOpDownload2phone extends AsyncTask<Object, Integer, Exception>{

		@Override
		protected Exception doInBackground(Object... objs) {

			AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("phoneNum", objs[0].toString()));
			params.add(new BasicNameValuePair("action", "downloadContacts"));
			
			try {
				HttpEntity entity = new UrlEncodedFormEntity(params,"UTF-8");
				httpPost.setEntity(entity);
				
				HttpResponse response = client.execute(httpPost);
				if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				//正常响应	
					InputStream is= response.getEntity().getContent();
					
				}else{
					
				}
			} catch (IOException e) {
				e.printStackTrace();
				return e;
			}finally{
				client.close();
			}
		
			return null;
		}
		
		@Override
		protected void onPreExecute() {
			pd.setMessage("正在从云端下载联系人...");
			pd.show();
		}
		
		@Override
		protected void onPostExecute(Exception result) {
			if(result == null){
				pd.dismiss();
				adb.setMessage("成功更新手机联系人！");
				adb.show();
			}else{
				pd.dismiss();
				adb.setMessage("下载失败，请重新操作！");
				adb.show();
			}
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
	}
	
	
	//private AsyncQueryHandler asyncQuery;
	class MyHandler extends Handler{
		public static final byte WHAT_CONTACT_EXPORT = 0;
		public static final byte WHAT_CONTACT_IMPORT = 1;
		public static final byte WHAT_REGIST = 2;
		public static final byte WHAT_BACKUP2NET = 3;
		public static final byte WHAT_DOWNLOAD2PHONE = 4;
		
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case WHAT_REGIST:
				break;
			case WHAT_CONTACT_EXPORT:
				/*pd.setMessage("正在将联系人导出到SD卡...");
				pd.show();
				List<ContactBean>  list= application.getContactBeanList();
				ArrayList<ContactBean> alist = new ArrayList<ContactBean>(list);
				try {
					if(sdOp.write(alist)){
						pd.dismiss();
						adb.setMessage("联系人导出成功！");
						adb.show();
					}else{
						pd.dismiss();
						adb.setMessage("导出失败，请重新操作！");
						adb.show();
					}
				} catch (IOException e1) {
					e1.printStackTrace();
					pd.dismiss();
				}*/
				
				break;
			case WHAT_CONTACT_IMPORT:
				
				/*ArrayList<ContactBean> alistR = null;
				try {
					pd.setMessage("正在将联系人导入手机...");
					pd.show();
					alistR = sdOp.read();
					//asyncQuery = new MyAsyncInsertHandler(getContentResolver());
					//Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 
					for(ContactBean bean: alistR){
						
						ContentValues values = new ContentValues();
						values.put(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, bean.getDisplayName());
						values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, bean.getPhoneNum());
						values.put(ContactsContract.CommonDataKinds.Phone.CONTACT_ID, bean.getContactId());
						values.put(ContactsContract.CommonDataKinds.Phone.PHOTO_ID, bean.getPhotoId());
						values.put(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY, bean.getLookUpKey());
						
						contentR.insert(uri, values);
						
						
						ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); 
						int rawContactInsertIndex = ops.size(); 
						ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
								.withValue(RawContacts.ACCOUNT_TYPE, null)
								.withValue(RawContacts.ACCOUNT_NAME, null)
								.build()); 
						 ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)   
					                .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)   
					                .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)   
					                .withValue(StructuredName.GIVEN_NAME, bean.getDisplayName())   
					                .build());   
					        ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)   
					                 .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)   
					                 .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)   
					                 .withValue(Phone.NUMBER, bean.getPhoneNum())   
					                 .withValue(Phone.TYPE, Phone.TYPE_MOBILE)   
					                 .build());   
					        
					        
							try {
								contentR.applyBatch(ContactsContract.AUTHORITY, ops);
							} catch (RemoteException e) {
								e.printStackTrace();
							} catch (OperationApplicationException e) {
								e.printStackTrace();
							}   
					}
					application.setContactBeanList(alistR);
					
					Intent it1 = new Intent();
					it1.setAction("UPDATE_CONTACT");
					sendBroadcast(it1); 
					pd.dismiss();
					adb.setMessage("导入联系人成功！");
					adb.show();
				} catch (OptionalDataException e) {
					e.printStackTrace();
					pd.dismiss();
					adb.setMessage("文件错误，不能正常导入联系人！");
					adb.show();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
					pd.dismiss();
					adb.setMessage("文件错误，不能正常导入联系人！");
					adb.show();
				} catch (IOException e) {
					e.printStackTrace();
					pd.dismiss();
					if(e instanceof FileNotFoundException){
						adb.setMessage("没有找到备份的文件，导入联系人失败！");
					}else{
						adb.setMessage("文件错误，不能正常导入联系人！");
					}
					adb.show();
				}
				
				if(alistR!=null){
					System.out.print("总共有联系人："+alistR.size());
				}*/
				break;
			case WHAT_BACKUP2NET:
				
				break;
			case WHAT_DOWNLOAD2PHONE:
				
				break;
			}
		}
	}
	
	
	private String userAgent = "";
	private String url = "http://hao.360.cn/home.html";
	private void webWorkGet(){
		AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
		HttpGet httpGet = new HttpGet(url);
		try {
			HttpResponse response = client.execute(httpGet);
			if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK){
			//正常响应	
			}else{
				
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		client.close();
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(sdOp!=null){
			sdOp.close();
		}
		
	}
}
